package com.fhz.day015;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

/**
 * 时间:2022/6/2
 *
 * @author msfeng
 * 简述: TODO
 */
public class MyTextView extends View {

    int defSize =0;
    int defHSize =0;

    float textSize = 0;
    String name;

    Paint paint;

    public MyTextView(Context context) {
        this(context,null);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        if(attrs != null){
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);
            textSize = typedArray.getDimension(R.styleable.MyTextView_textSize, 10f);
            name = typedArray.getString(R.styleable.MyTextView_name);
            typedArray.recycle();
        }
    }

    //必须要重写,计算自己的包裹内容的大小.
    //应为源码里面wrap 和match是一个逻辑.
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int mode = MeasureSpec.getMode(widthMeasureSpec);
        int size = MeasureSpec.getSize(widthMeasureSpec);
        switch (mode) {
            case MeasureSpec.UNSPECIFIED:
                defHSize = size;
                break;
            case MeasureSpec.AT_MOST:
                defHSize = 1000; //根据内容的大小是px
                break;
            case MeasureSpec.EXACTLY: //match . 固定值
                defHSize = size;
                break;
        }

        int Hmode = MeasureSpec.getMode(heightMeasureSpec);
        int Hsize = MeasureSpec.getSize(heightMeasureSpec);
        switch (Hmode) {
            case MeasureSpec.UNSPECIFIED:
                defSize = Hsize;
                break;
            case MeasureSpec.AT_MOST:
                defSize = 1000; //根据内容的大小
                break;
            case MeasureSpec.EXACTLY:
                defSize = Hsize;
                break;
        }

        setMeasuredDimension(MeasureSpec.makeMeasureSpec(defSize,mode),MeasureSpec.makeMeasureSpec(defHSize,Hmode));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
//        canvas.drawColor(Color.BLACK);
        paint.setColor(Color.RED);
        paint.setTextSize(textSize);
        canvas.drawText(name,100,100,paint);

    }
}

